package com.ybkj.daijia.server.service.impl;

import static org.apache.commons.codec.binary.Base64.encodeBase64;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.api.driver.ErrorConstant;
import com.ybkj.daijia.serverUtils.AliBabaHttpUtils;
import com.ybkj.daijia.serverUtils.IOUtils;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Service;

/**
 * @author zhyu
 * @date 2019/12/26 10:32
 */
@Service
@Slf4j
public class OcrServiceImpl {



    public boolean faceCompare(String base64, Long driverId){
        return false;
    }

    public JSONObject ocrService2(String base64, String type) {
        String host = "https://dm-52.data.aliyun.com";
        String path = "/rest/160601/ocr/ocr_driver_license.json";
        String appcode = "a58afc8611bf4def9fbde7bb57851bf3";
        String imgFile = "G://images/driver1licensee.png";
        //如果文档的输入中含有inputs字段，设置为True， 否则设置为False
        Boolean is_old_format = false;
        //请根据线上文档修改configure字段
        JSONObject configObj = new JSONObject();
        configObj.put("side", "face");
        String config_str = configObj.toString();
        String method = "POST";
        Map<String, String> headers = new HashMap();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        headers.put("Authorization", "APPCODE " + appcode);

        Map<String, String> querys = new HashMap();

        // 对图像进行base64编码
        String imgBase64 = "";
        try {
            File file = new File(imgFile);
            byte[] content = new byte[(int) file.length()];
            FileInputStream finputstream = new FileInputStream(file);
            finputstream.read(content);
            finputstream.close();
            imgBase64 = new String(encodeBase64(content));
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 拼装请求body的json字符串
        JSONObject requestObj = new JSONObject();
        try {
            if(is_old_format) {
                JSONObject obj = new JSONObject();
//                obj.put("image", getParam(50, imgBase64));
                if(config_str.length() > 0) {
//                    obj.put("configure", getParam(50, config_str));
                }
                JSONArray inputArray = new JSONArray();
                inputArray.add(obj);
                requestObj.put("inputs", inputArray);
            }else{
                requestObj.put("image", imgBase64);
                if(config_str.length() > 0) {
                    requestObj.put("configure", config_str);
                }
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String bodys = requestObj.toString();

        try {
            HttpResponse response = AliBabaHttpUtils.doPost(host, path, method, headers, querys, bodys);
            int stat = response.getStatusLine().getStatusCode();
            if(stat != 200){
                System.out.println("Http code: " + stat);
                System.out.println("http header error msg: "+ response.getFirstHeader("X-Ca-Error-Message"));
                System.out.println("Http body error msg:" + EntityUtils.toString(response.getEntity()));
                return null;
            }

            String res = EntityUtils.toString(response.getEntity());
            JSONObject res_obj = JSON.parseObject(res);
            if(is_old_format) {
                JSONArray outputArray = res_obj.getJSONArray("outputs");
                String output = outputArray.getJSONObject(0).getJSONObject("outputValue").getString("dataValue");
                JSONObject out = JSON.parseObject(output);
                System.out.println(out.toJSONString());
            }else{
                System.out.println(res_obj.toJSONString());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public JSONObject ocrService(String base64, String type) {
        //{"bank_name":"中国建设银行","card_num":"6230943660000675270","request_id":"20191226104651_94aec81bd3c114570474a93a7b5d42bd","success":true,"valid_date":"02/29"}
        String host = "https://yhk.market.alicloudapi.com";
        String path = "/rest/160601/ocr/ocr_bank_card.json";
        String method = "POST";
        String appcode = Constant.APPCODE;
        Map<String, String> headers = new HashMap();
        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/json; charset=UTF-8");
        Map<String, String> querys = new HashMap();
        String str = IOUtils.readFileToBase64(base64);
        if (str != null) {
            String bodys = "{\"image\":\"" +  str + "\"}";
            try {
                HttpResponse response = AliBabaHttpUtils.doPost(host, path, method, headers, querys, bodys);
                if(HttpStatus.SC_OK == response.getStatusLine().getStatusCode()) {
                    HttpEntity entity = response.getEntity();
                    InputStream content = response.getEntity().getContent();
                    byte[] bytes = new byte[content.available()];
                    content.read(bytes);
                    JSONObject jsonObject = JSON.parseObject(new String(bytes));
                    if (jsonObject.getBoolean("success").equals(Boolean.TRUE)) {
                        jsonObject.remove("request_id");
                        jsonObject.remove("valid_date");
                        jsonObject.remove("success");
                        return jsonObject;
                    }
                }
            } catch (Exception e) {
                if (log.isErrorEnabled()) {
                    log.error("ocr错误", e);
                }
            }
        }
        throw ErrorConstant.IMAGE_OCR_ERROR.changeToCanThrowToUserException();
    }
}
